<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <!-- <el-form-item label="知识库id" prop="ragId">
        <el-input
          v-model="queryParams.ragId"
          placeholder="请输入知识库id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="文档名称" prop="docName">
        <el-input
          v-model="queryParams.docName"
          placeholder="请输入文档名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文档类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择文档类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.bjj_rag_doc_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="minio地址" prop="remoteUrl">
        <el-input
          v-model="queryParams.remoteUrl"
          placeholder="请输入minio地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="保密等级" prop="serectLevel">
        <el-select
          v-model="queryParams.serectLevel"
          placeholder="请选择保密等级"
          clearable
        >
          <el-option
            v-for="dict in dict.type.bjj_rag_doc_secret_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.bjj_rag_doc_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上传日期" prop="createDate">
        <el-date-picker
          clearable
          v-model="queryParams.createDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择上传日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:doc:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:doc:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:doc:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['manage:doc:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="docList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="文档标题" align="center" prop="docId" /> -->
      <el-table-column label="文档名称" align="center" prop="docName" />
      <el-table-column label="所属知识库" align="center" prop="rag.ragTitle" />
      <el-table-column label="上传用户" align="center" prop="user.nickName" />
      <el-table-column label="文档类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bjj_rag_doc_type"
            :value="scope.row.type"
          />
        </template>
      </el-table-column>
      <el-table-column label="作者" align="center" prop="author" />
      <!-- <el-table-column label="minio地址" align="center" prop="remoteUrl" /> -->
      <el-table-column label="保密等级" align="center" prop="serectLevel">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bjj_rag_doc_secret_level"
            :value="scope.row.serectLevel"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bjj_rag_doc_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="上传日期"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:doc:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            :disabled="scope.row.status == '1'"
            @click="handleSolve(scope.row)"
            v-hasPermi="['manage:doc:edit']"
            >解析</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:doc:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改知识库附属文档信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-row :gutter="10">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-col :span="10">
            <el-form-item label="文档名称" prop="docName">
              <el-input
                v-model="form.docName"
                placeholder="请输入文档名称"
                size="medium"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="文档类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择文档类型"
                style="width: 300px"
              >
                <el-option
                  v-for="dict in dict.type.bjj_rag_doc_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input
                v-model="form.author"
                placeholder="请输入作者"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="保密等级" prop="serectLevel">
              <el-select
                v-model="form.serectLevel"
                placeholder="请选择保密等级"
                style="width: 300px"
              >
                <el-option
                  v-for="dict in dict.type.bjj_rag_doc_secret_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="form.status"
                placeholder="请选择状态"
                style="width: 300px"
                :disabled="form.status == 1"
              >
                <el-option
                  v-for="dict in dict.type.bjj_rag_doc_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传日期" prop="createDate">
              <el-date-picker
                clearable
                v-model="form.createDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择上传日期"
                style="width: 300px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item prop="remoteUrl">
              <el-upload
                class="upload-demo"
                drag
                action=""
                :http-request="uploadFile"
                :before-upload="beforeUpload"
                :show-file-list="true"
                accept=".pdf,.txt,.xlsx,.xls,.doc,.docx,.jpg,.jpeg,.png"
                
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">
                  仅支持上传 PDF、TXT、Excel、DOC、DOCX 和图片文件,且不超过20M
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listDoc, getDoc, delDoc, addDoc, updateDoc,uploadDoc,solveDoc,updateDocStatus } from "@/api/manage/doc";
import { createLogger } from "vuex";

export default {
  name: "Doc",
  dicts: ["bjj_rag_doc_status", "bjj_rag_doc_secret_level", "bjj_rag_doc_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识库附属文档信息表格数据
      docList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ragId: null,
        userId: null,
        docName: null,
        type: null,
        author: null,
        remoteUrl: null,
        serectLevel: null,
        status: null,
        createDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // uploadUrl:process.env.VUE_APP_BASE_API+'/manage/doc/upload'
    };
  },
  created() {
    this.queryParams.ragId = this.$route.params && this.$route.params.id;
    this.queryParams.userId = this.$store.getters.id;
    this.getList();
  },
  methods: {
    judge_if_empty(){
      if(this.form.remoteUrl!=''){
        this.$message.warning('已上传文件，暂不支持修改');
      }
    },
    handleSolve(row) {
      solveDoc(row.docId).then((response) => {
        if(response.data !== "导入失败"){
          this.$modal.msgSuccess("解析成功");
          updateDocStatus(row.docId,'1').then((response) => {
              this.getList();
          });
        }
        else{
          this.$modal.msgError("解析失败");
        }
      });
    },
  
    beforeUpload(file) {
      const allowedTypes = [
        "application/pdf",
        "text/plain",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.ms-excel",
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "image/jpeg",
        "image/png",
      ];
      if (!allowedTypes.includes(file.type)) {
        this.$message.error("仅支持上传 PDF、TXT、Excel、DOC、DOCX 和图片文件");
        return false;
      }
      return true;
    },
    uploadFile({file}){
      const formData = new FormData();
      formData.append("file", file);
      uploadDoc(formData).then((response) => {
        // console.log(response) 
        if(response.data.message === true){
          this.form.remoteUrl = response.data.download_url ;
          this.form.fileName = response.data.file_name ;
          this.$message.success("上传成功");
        }else{
          this.$message.error(response.data);
        }
      })
    },
    /** 查询知识库附属文档信息列表 */
    getList() {
      this.loading = true;
      listDoc(this.queryParams).then((response) => {
        this.docList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        docId: null,
        ragId: null,
        userId: null,
        docName: null,
        type: null,
        author: null,
        remoteUrl: null,
        serectLevel: null,
        status: null,
        createDate: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据  */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.docId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增文档信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const docId = row.docId || this.ids;
      getDoc(docId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文档信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.docId != null) {
            updateDoc(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.ragId = this.$route.params && this.$route.params.id;
            this.form.userId = this.$store.getters.id;
            addDoc(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const docIds = row.docId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除知识库附属文档信息编号为"' + docIds + '"的数据项？'
        )
        .then(function () {
          return delDoc(docIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "manage/doc/export",
        {
          ...this.queryParams,
        },
        `doc_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
